package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.serve.dto.AlertDataDto;
import com.zzyl.serve.dto.HandleAlertDataDto;
import com.zzyl.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.AlertDataMapper;
import com.zzyl.serve.domain.AlertData;
import com.zzyl.serve.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;

/**
 * 报警数据Service业务层处理
 *
 * @author iteheima
 * @date 2025-03-18
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警数据列表
     *
     *
     * @return 报警数据
     */
    @Override
    public List<AlertData> selectAlertDataList(Integer pageNum,Integer pageSize,String deviceName,Integer status, LocalDateTime startTime, LocalDateTime endTime) {
        // 获得当前登录人的id,谁登录谁就只能看到谁的
        Long userId = SecurityUtils.getUserId();
        //定义分页参数-
       Page ipage= Page.of(pageNum,pageSize);
       LambdaQueryWrapper<AlertData> lqw=new LambdaQueryWrapper<>();
       //每个角色只能看到跟自己有关的数据,然后超级管理员可以查到全部的数据
        lqw.eq(AlertData::getUserId,userId)
                .like(StringUtils.isNotBlank(deviceName),AlertData::getDeviceName,deviceName)
                .eq(status!=null,AlertData::getStatus,status)
                .between(ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isNotEmpty(endTime),
                        AlertData::getCreateTime,
                        startTime,
                       endTime
                );
        //重新返回给分页参数
        page(ipage,lqw);
        return ipage.getRecords();
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public int handleAlertData(HandleAlertDataDto handleAlertDataDto) {

        //获得当前登录id
        Long userId = SecurityUtils.getUserId();
        //根据id获得当前登录人
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        String nickName = sysUser.getNickName();


        //比如我们有一个异常会同时通知很多人,超级管理员和维修工或者是护理员,只有有一个人处理了其他的人都看不到了,我们只需要
        //同一时间同一设备的异常
        AlertData byId = getById(handleAlertDataDto.getId());
        byId.getDeviceName();
        byId.getCreateTime();
        //找到跟这个设备名字一样且创建时间一样的数据
        List<AlertData> alertDataList = list(
                new LambdaQueryWrapper<AlertData>()
                        .eq(AlertData::getDeviceName, byId.getDeviceName())
                        .eq(AlertData::getCreateTime, byId.getCreateTime())
        );
        //遍历集合然后赋值
        alertDataList.forEach(alertData -> {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(handleAlertDataDto.getProcessingTime(), DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            alertData.setProcessingTime(activeTime);
            alertData.setProcessingResult(handleAlertDataDto.getProcessingResult());
            alertData.setStatus(1);
            alertData.setProcessorId(userId);
            alertData.setProcessorName(nickName);
        });
        return updateBatchById(alertDataList) ? 1 : 0;


    }
}
